<?php

namespace App\Jobs\Search;

use App\Models\Circle\WxCircle;
use App\Models\Posts\WxPost;
use App\Models\Shop\WxShopGoods;
use App\Models\User\WxUser;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ElasticSearchBatchSyncJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 1;
    protected $maxId = 1000;
    protected $minId = 0;
    protected $type = 'post';
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($minId, $maxId, $type)
    {
        $this->minId = $minId;
        $this->maxId = $maxId;
        $this->type = $type;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        if($this->type == 'post'){
            WxPost::where('id', '>', $this->minId)->where('id', '<=', $this->maxId)->where('is_examine', 1)->where('posts_state', 0)->searchable();
            if(WxPost::where('id', '>', $this->maxId)->where('is_examine', 1)->where('posts_state', 0)->exists()){
                ElasticSearchBatchSyncJob::dispatch($this->maxId, $this->maxId + 1000, $this->type)->delay(now()->addSeconds(10));
            }else{
                return;
            }
        }else if($this->type == 'user'){
            WxUser::where('id', '>', $this->minId)->where('id', '<=', $this->maxId)->where('user_state', 0)->searchable();
            if(WxUser::where('id', '>', $this->maxId)->where('user_state', 0)->exists()){
                ElasticSearchBatchSyncJob::dispatch($this->maxId, $this->maxId + 1000, $this->type)->delay(now()->addSeconds(10));
            }else{
                return;
            }
        }else if($this->type == 'circle'){
            WxCircle::where('id', '>', $this->minId)->where('id', '<=', $this->maxId)->where('circle_state', 1)->searchable();
            if(WxCircle::where('id', '>', $this->maxId)->where('circle_state', 1)->exists()){
                ElasticSearchBatchSyncJob::dispatch($this->maxId, $this->maxId + 1000, $this->type)->delay(now()->addSeconds(10));
            }else{
                return;
            }
        }else if($this->type == 'goods'){
            WxShopGoods::where('id', '>', $this->minId)->where('id', '<=', $this->maxId)->where('state', 1)->searchable();
            if(WxShopGoods::where('id', '>', $this->maxId)->where('state', 1)->exists()){
                ElasticSearchBatchSyncJob::dispatch($this->maxId, $this->maxId + 1000, $this->type)->delay(now()->addSeconds(10));
            }else{
                return;
            }
        }
    }
}
